import React, { Component } from 'react';
import styles from './index.module.scss';

import { conversationList, conversation } from '@/api/ai';
import { connect } from 'react-redux';
import { update } from '@/utils/immutableUtil';
import { withConsumer } from '../context';

@withConsumer
@connect(({ chat }) => ({
  chatsList: chat.chatsList,
}))
class Comp extends Component {
  componentDidMount = async () => {
    this.props.init(this);
    const {
      value: { changeState, event },
    } = this.props;
    this.throttledGetList((data) => {
      var selectedChat = '';
      if (typeof window !== 'undefined') {
        selectedChat = window.localStorage.getItem('selectedChat');
      }

      var selectedItem = null;
      data.forEach((item) => {
        if (String(item.id) == selectedChat) {
          selectedItem = item;
        }
      });

      var obj = {
        selectedChat: selectedChat ? selectedChat : null,
        selectedItem: selectedItem,
        selectedChatInit: true,
      };

      if (selectedItem) {
        this.getChatDetail(selectedChat);
      } else {
        setTimeout(() => {
          event.emit('newChat');
        }, 50);
      }

      changeState(obj);
    });
  };

  throttledGetList = (callback = () => {}) => {
    this.getList(callback);
  };

  // 回话列表
  getList = async (back = () => {}) => {
    const {
      value: { changeState },
    } = this.props;
    var rs = await conversationList();
    if (rs.data?.code == 200) {
      var data = rs.data.data.map((item) => {
        return {
          ...item,
          title: item.theme,
          date: item.created,
        };
      });
      changeState({ chatsList: data });
      setTimeout(() => {
        back(data);
      }, 10);
    }
  };

  // 回话详情
  getChatDetail = async (chatId) => {
    const {
      value: { event, changeState },
    } = this.props;
    var rs = await conversation({ conversation_id: chatId });
    if (rs.data?.code == 200) {
      var data = rs.data.data;
      if (!data) return;
      var list = data.dialog_segment_list.map((item, i) => {
        var types = ['ppt', 'svger', 'artifacts'];

        var obj = {
          ...item,
          object: null,
          role: item.role,
          content: [],
          text: item.content,
          dialog_segment_id:item.id
        };

        // ppt
        if (item.payload.json_type == 'ppt') {
          obj.ppt = {
            id: item.id,
            code: item.content,
            thinking: '',
            type: '1',
            width: 1280,
            height: 720,
            isEdn: true,
          };
        }

        // svger
        if (item.payload.json_type == 'svger') {
          obj.svger = {
            svg: item.content,
          };
        }

        // artifacts
        if (item.payload.json_type == 'artifacts') {
          var atrStr = item.content || '';
          atrStr = atrStr.replace(/```[\w-]*\n?/g, '');
          atrStr = atrStr.replace(/^[\w-]*\n?/, '');
          var itemObj = JSON.parse(atrStr);
          obj.object = itemObj;
          obj.content = [
            { type: 'text', text: itemObj.commentary || '' },
            { type: 'code', text: itemObj.code || '' },
          ];
        }

        // 正常消息
        var defMsg = types.indexOf(item.payload.json_type) == -1;
        if (defMsg && item.content) {
          if (Array.isArray(item.content)) {
            var attr = [];
            item.content.forEach((ite, i) => {
              attr.push({
                ...ite,
                text: ite.content,
                itemData: item,
              });
            });
            obj.content = attr;
          } else {
            obj.content = [
              {
                type: 'text',
                text: item.content,
                itemData: item,
              },
            ];
          }
        }

        return obj;
      });
      event.emit('onChatClick', list);
    }
  };

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  render() {
    return <div></div>;
  }
}

export default Comp;
